package com.ys.service.mall.impl;

import java.math.BigDecimal;
import java.util.Date;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.bo.vo.R;
import com.ys.entity.finance.TcwAccountCountForUser;
import com.ys.entity.mall.TmGoods;
import com.ys.entity.mall.TmOrder;
import com.ys.entity.mall.TmGift;
import com.ys.entity.shiro.LoginUser;
import com.ys.enume.finance.TcwUserPointFrozenRunningEnum;
import com.ys.enume.finance.TcwUserPointRunningEnum;
import com.ys.enume.mall.TmGoodsStockRunningEnum;
import com.ys.enume.mall.TmGiftEnum;
import com.ys.mapper.mall.TmOrderMapper;
import com.ys.mapper.mall.TmGiftMapper;
import com.ys.service.finance.TcwAccountCountForUserService;
import com.ys.service.finance.TcwAccountCountForUserService.ChangePointDto;
import com.ys.service.finance.TcwAccountCountForUserService.ChangePointFrozenDto;
import com.ys.service.mall.TmGoodsService;
import com.ys.service.mall.TmOrderService;
import com.ys.util.DateUtil;
import com.ys.util.OrderUtil;
import com.ys.util.shiro.ShiroUtils;

@Service("tmOrderService")
public class TmOrderServiceImpl implements TmOrderService {

	@Autowired
	private TmOrderMapper tmOrderMapper;
	@Autowired
	private TmGiftMapper tmGiftMapper;
	
	@Autowired
	private TmGoodsService tmGoodsService;
	@Autowired
	private TcwAccountCountForUserService tcwAccountCountForUserService;
	
	@Override
	@Transactional
	public R commit(Long goodsId, Integer num, String address) throws Exception {
		if (goodsId == null) {
			return R.error("商品ID不能为空");
		}
		TmGoods tmGoods = new TmGoods().setId(goodsId).queryFirst();
		if (tmGoods == null) {
			return R.error("商品不存在");
		}
		
		// 验证库存
		if (num < 1) {
			return R.error("数量不能少于1");
		}
		if (tmGoods.getStockNum() < num) {
			return R.error("库存不足");
		}
		
		BigDecimal amountTotal = tmGoods.getAmount().multiply(new BigDecimal(num));
		
		LoginUser loginUser = ShiroUtils.getLoginUser();
		String userId = loginUser.getUserId();
		String userName = loginUser.getUserName();
		TcwAccountCountForUser tcwAccountCountForUser = new TcwAccountCountForUser().setUserId(userId).queryFirst();
		// 验证积分余额
		if (amountTotal.compareTo(tcwAccountCountForUser.getPoint()) > 0) {
			return R.error("积分不足");
		}
		
		// 添加订单
		TmOrder entity = null;
		{
			String code = generateOrderCode();
			String goodsCode = tmGoods.getCode();
			String goodsName = tmGoods.getName();
			BigDecimal amount = amountTotal;
			entity = TmOrder.tmOrder(code, goodsId, goodsCode, goodsName, userId, amount, num, address, 1);
			tmOrderMapper.insert(entity);
		}
		
		// 扣除用户学分并添加流水
		{
			ChangePointDto changePointDto = null;
			{
				String item = "兑换礼品";
				String itemSub = "兑换礼品";
				Integer type = TcwUserPointRunningEnum.Type.BUY_ORDER.value;
				Long relativeId = entity.getId();
				BigDecimal pointChange = amountTotal.negate();
				String remark = "兑换礼品，订单号：" + entity.getCode();
				changePointDto = new ChangePointDto(item, itemSub, type, relativeId, userId, userName, pointChange, remark);
			}
			ChangePointFrozenDto changePointFrozenDto = null;
			tcwAccountCountForUserService.change(changePointDto, changePointFrozenDto);
		}
		
		// 扣除库存数量，同时添加礼品库存流水
		{
			Integer type = TmGoodsStockRunningEnum.Type.BUY_ORDER.value;
			Integer numChange = num * -1;
			String remark = "兑换礼品";
			Long relativeId = entity.getId();
			tmGoodsService.changeNum(goodsId, type, numChange, remark, relativeId);
		}
		
		// 添加用户礼品
		for (int i = 0; i < num; i++) {
			String code = generateGiftCode();
			String goodsCode = tmGoods.getCode();
			String goodsImg = tmGoods.getImg();
			String goodsName = tmGoods.getName();
			Integer sourceType = TmGiftEnum.SourceType.BUY_ORDER.value;
			Long sourceId = entity.getId();
			Date invalidTime = DateUtil.addDays(new Date(), tmGoods.getValidDays());
			Integer state = TmGiftEnum.State.ABLE.value;
			TmGift tmGift = TmGift.tmGift(userId, code, goodsId, goodsCode, goodsImg, goodsName, sourceType, sourceId, invalidTime, state, 1);
			tmGiftMapper.insert(tmGift);
		}
		
		return R.ok("操作成功");
	}

	/**
	 * 生成订单编码
	 */
	@Override
	public String generateOrderCode() {
		String today = DateUtil.getYYYY_MM_DD(new Date());
		String num = "" + (new TmGift()
				.where("A.CreateTime >= '" + today + " 00:00:00'")
				.where("A.CreateTime <= '" + today + " 23:59:59'")
				.count() + 1);
		
		return "LPDD" + (today.substring(2).replace("-", "")) + (OrderUtil.createZero(5 - num.length()) + num);
	}

	/**
	 * 生成用户礼品编码
	 */
	@Override
	public String generateGiftCode() {
		String today = DateUtil.getYYYY_MM_DD(new Date());
		String num = "" + (new TmGift()
				.where("A.CreateTime >= '" + today + " 00:00:00'")
				.where("A.CreateTime <= '" + today + " 23:59:59'")
				.count() + 1);
		
		return "LPBS" + (today.substring(2).replace("-", "")) + (OrderUtil.createZero(5 - num.length()) + num);
	}
}
